package com.lemon.core.common.lang.template;

import com.lemon.core.common.lang.constant.Constants;
import com.lemon.core.common.lang.util.ResourceUtils;
import com.lemon.core.common.lang.util.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @author hdzhang
 * @ClassName VelocityUtils
 * @desc velocity工具类
 * @Date 2018/8/27 9:59
 * @Version 1.0
 **/
public class VelocityUtils {

    /**
     * 通过数据构造velocity上下文
     * @param list  填充模板的数据
     * @return
     */
    public static VelocityContext buildContext(List<HashMap<String, Object>> list) {
        VelocityContext context = new VelocityContext();
        context.put("list", list);
        return context;
    }

    /**
     * 填充vm模板文件
     * @param outputFilePath
     * @param tmplPath
     * @param context
     */
    public static void generateTmplFile(VelocityContext context, String tmplPath, String outputFilePath) {
        String projectPath = ResourceUtils.getProjectPath();
        if (StringUtils.isBlank(projectPath)) {
            return;
        }

        //得到VelocityEngine
        VelocityEngine engine = new VelocityEngine();

        Properties properties = new Properties();
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, projectPath);
        engine.init(properties);

        //得到模板文件
        Template template = engine.getTemplate(tmplPath, Constants.UTF_8);

        FileWriter fileWriter = null;
        try {
            //生成xml
            fileWriter = getFileWriter(outputFilePath);
            //调用merge方法传入context
            template.merge(context, fileWriter);
            // 刷新流
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fileWriter) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取文件写入流
     * @param outputFilePath
     * @return
     * @throws IOException
     */
    private static FileWriter getFileWriter(String outputFilePath) throws IOException {
        File outputFile = new File(outputFilePath);
        return new FileWriter(outputFile);
    }
}
